<template>
  <div class="flex">
    <!-- 筛选侧边栏 -->
    <div class="w-200px mr-20px">
      <ContentWrap class="!mb-0">
        <div class="tree-container">
          <el-tree
            ref="treeRef"
            :data="treeData"
            :props="defaultProps"
            node-key="id"
            highlight-current
            check-on-click-node
            accordion
            :expand-on-click-node="false"
            default-expand-all
            :current-node-key="currentNodeKey"
            @current-change="handleNodeClick"
          />
        </div>
      </ContentWrap>
    </div>

    <!-- 主内容区 -->
    <div class="flex-1">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="菜谱名称" prop="recipeName">
            <el-input
              v-model="queryParams.recipeName"
              placeholder="请输入菜谱名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button @click="handleQuery"
              ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
            >
            <el-button @click="resetQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button
            >
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['school:recipes:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
            <!-- <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['school:recipes:export']"
            >
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button> -->
            <!-- <el-button
              type="danger"
              plain
              :disabled="isEmpty(checkedIds)"
              @click="handleDeleteBatch"
              v-hasPermi="['school:recipes:delete']"
            >
              <Icon icon="ep:delete" class="mr-5px" /> 批量删除
            </el-button> -->
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table
          row-key="id"
          v-loading="loading"
          :data="list"
          :stripe="true"
          :show-overflow-tooltip="true"
          @selection-change="handleRowCheckboxChange"
        >
          <!-- <el-table-column type="selection" width="55" /> -->
          <el-table-column label="菜谱ID" align="center" prop="recipeId" />
          <el-table-column label="菜谱名称" align="center" prop="recipeName" />
          <el-table-column label="查看食材" align="center">
            <template #default="scope">
              <el-popover
                placement="right"
                :width="300"
                trigger="click"
                @show="loadFoodList(scope.row)"
              >
                <template #reference>
                  <el-button link type="primary">查看食材</el-button>
                </template>
                <el-table
                  :data="scope.row.foodList"
                  v-loading="scope.row.foodLoading"
                  style="width: 100%"
                  max-height="300"
                >
                  <el-table-column prop="foodName" label="食材名称" />
                  <el-table-column prop="usage" label="用量(克)" />
                </el-table>
                <div
                  class="flex justify-center mt-4"
                  v-if="
                    !scope.row.foodLoading && scope.row.foodList && scope.row.foodList.length === 0
                  "
                >
                  <el-empty description="暂无食材数据" :image-size="80" />
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="菜谱分类" align="center" prop="recipeTypeName" />
          <!-- <el-table-column label="食材" align="center" prop="foods" /> -->
          <el-table-column label="描述" align="center" prop="description" />
          <el-table-column label="排序" align="center" prop="sort" />
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          /> -->
          <el-table-column label="操作" align="center" min-width="120px">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['school:recipes:update']"
              >
                编辑
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['school:recipes:delete']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </div>
  </div>

  <!-- 表单弹窗：添加/修改 -->
  <RecipesForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
// 树节点数据结构定义
interface TreeDataItem {
  id: number
  name: string
  typeId?: string
  leaf?: boolean
  children?: TreeDataItem[]
}

interface RecipesItem extends Recipes {
  foodList?: Array<{
    foodTypeId: string
    foodId: string
    foodName: string
    usage: number
  }>
  foodLoading?: boolean
}

import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import download from '@/utils/download'
import { RecipesApi, Recipes } from '@/api/school/recipe/recipes'
import RecipesForm from './RecipesForm.vue'
import { RecipesTypeApi, RecipesType } from '@/api/school/recipe/recipeType'
import { ElTree } from 'element-plus'
import { defaultProps } from '@/utils/tree'
import { useI18n } from 'vue-i18n'
import { useMessage } from '@/hooks/web/useMessage'
import { ref, reactive, onMounted } from 'vue'

/** 菜谱 列表 */
defineOptions({ name: 'Recipes' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<RecipesItem[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams: any = reactive({
  pageNo: 1,
  pageSize: 10,
  recipeId: undefined,
  recipeName: undefined,
  recipeTypeId: undefined,
  status: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 树相关
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeData = ref<TreeDataItem[]>([])
const currentNodeKey = ref(0) // 控制当前选中的节点key

/** 查询菜谱分类列表 */
const getRecipeTypeTree = async () => {
  try {
    // 获取菜谱分类列表
    const res = await RecipesTypeApi.getRecipesTypeSimpleList()

    // 构造树形结构，添加"全部菜谱"作为根节点
    const allRecipesNode: TreeDataItem = {
      id: 0,
      name: '全部菜谱',
      leaf: false,
      children: res.map((item: RecipesType) => ({
        id: item.id,
        name: item.typeName,
        leaf: true,
        typeId: item.typeId // 保存typeId字段
      }))
    }

    treeData.value = [allRecipesNode]

    // 通过currentNodeKey控制默认选中"全部菜谱"节点
    currentNodeKey.value = 0
  } catch (e) {
    console.error('获取菜谱分类数据失败:', e)
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await RecipesApi.getRecipesPage(queryParams)
    // 初始化foodList和foodLoading属性
    data.list.forEach((item) => {
      item.foodList = []
      item.foodLoading = true
    })
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  // 重置分类筛选为"全部菜谱"
  currentNodeKey.value = 0
  queryParams.recipeTypeId = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await RecipesApi.deleteRecipes(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除菜谱 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await RecipesApi.deleteRecipesList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Recipes[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RecipesApi.exportRecipes(queryParams)
    download.excel(data, '菜谱.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 处理节点点击 */
const handleNodeClick = (data: TreeDataItem) => {
  // 更新currentNodeKey的值
  currentNodeKey.value = data.id

  // 如果是根节点"全部菜谱"，则清空分类筛选条件
  if (data.id === 0) {
    queryParams.recipeTypeId = undefined
  } else {
    // 否则设置对应的分类ID（使用typeId字段）
    queryParams.recipeTypeId = data.typeId
  }

  // 重置页码并重新查询
  queryParams.pageNo = 1
  handleQuery()
}

/**
 * 获取食材列表
 * @param row 菜谱行数据
 */
const loadFoodList = async (row) => {
  // 如果已经加载过食材数据，则直接返回
  if (row.foodList && row.foodList.length > 0) {
    return
  }

  // 只有当foodList未初始化时才显示加载状态
  if (!row.foodList) {
    row.foodLoading = true
  }

  try {
    const res = await RecipesApi.getRecipes(row.id)
    row.foodList = res.foodList || []
  } catch (err) {
    message.error('获取食材列表失败')
    console.error(err)
    // 出错时初始化为空数组，避免持续显示加载状态
    row.foodList = []
  } finally {
    row.foodLoading = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getRecipeTypeTree()
})
</script>

<style lang="scss" scoped>
.tree-container {
  height: calc($content-height - 22px);
  overflow-y: auto;
}
</style>
